package com.gjy.util.file;

import org.apache.commons.lang3.ArrayUtils;

import java.io.File;
import java.io.FileInputStream;
import java.security.MessageDigest;
import java.util.List;

/**
 * @author 宫静雨
 * @version 1.0
 * @since 2023-11-25 14:14:46
 */
public class FileUtil {

    public static void innerListFiles(List<File> files, File directory, boolean sub) {
        File[] found = directory.listFiles();
        if (ArrayUtils.isNotEmpty(found)) {
            for (File file : found) {
                if (file.isDirectory()) {
                    if (sub) {
                        files.add(file);
                    }
                    innerListFiles(files, file, sub);
                } else {
                    files.add(file);
                }
            }
        }
    }

    // 获取文件的md5
    public static String getFileMD5(String fileName) {
        StringBuilder result = new StringBuilder();
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            File file = new File(fileName);
            FileInputStream fis = new FileInputStream(file);
            byte[] buffer = new byte[1024];
            int length;
            while ((length = fis.read(buffer)) != -1) {
                md.update(buffer, 0, length);
            }
            byte[] bytes = md.digest();
            for (byte b : bytes) {
                result.append(Integer.toHexString(b & 0xff));
            }
            fis.close();
            return result.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;  // 返回null表示异常
        }
    }

    // 遍历一个文件夹下所有文件名,并返回一个List
    public static String[] getFileName(String path) {
        File file = new File(path);
        File[] files = file.listFiles();
        assert files != null;
        String[] fileNames = new String[files.length];
        for (int i = 0; i < files.length; i++) {
            fileNames[i] = files[i].getName();
        }
        return fileNames;
    }

}
